<?php
class NewsModel extends CI_Model {
	
	function __construct() {
		parent::__construct ();
	}
	
	function getNews($slug = FALSE) {
		if ($slug === FALSE) {
			$query = $this->db->get ( 'news' );
			return $query->result_array ();
		} else {
			$query = $this->db->get_where ( 'news', array ('slug' => $slug ) );
			return $query->row_array ();
		}
	}
	
	function get($id=0,$limit=0,$offset=0){
		if(!is_numeric($id) || !is_numeric($limit) || $id < 0 || $limit < 0)
			return null;
		if($id == 0){
			if($limit > 0)
				$this->db->limit($limit,$offset);
			$query = $this->db->get('news');
			return $query->result();
		}else{
			$this->db->where('id',$id);
			$query = $this->db->get('news');
			if($query->num_rows() > 0)
				return $query->first_row();
		}
	}
	
	
	public function create() {
		$this->load->helper ( 'url' );
		$slug = url_title ( $this->input->post ( 'title' ), 'dash', TRUE );
		$data = array ('title' => $this->input->post ( 'title' ), 'slug' => $slug, 'text' => $this->input->post ( 'text' ) );
		return $this->db->insert ( 'news', $data );
	}
	
	function delete($id) {
		$this->db->where ( 'id', $id );
		$query = $this->db->delete ( 'news' );
		if (! $query)
			return false;
		else
			return true;
	}
	
	function update($id, $data) {
		foreach ( $data as &$d ) {
			$d = $this->db->escape_str ( $d );
		}
		if (isset ( $data ['title'] )) {
			$newdata ['title'] = $data ['title'];
		}
		if (isset ( $data ['text'] )) {
			$newdata ['text'] = $data ['text'];
		}
		
		$this->db->where ( 'id', $id );
		$query = $this->db->get ( 'news' );
		
		if ($query->num_rows () == 0)
			return false;
		else {
			$this->db->where ( 'id', $id );
			if ($this->db->update ( 'news', $newdata ))
				return true;
			else
				return false;
		}
	}
}